//
//  TestGridPageTableViewCell.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2022/2/22.
//  Copyright © 2022 moon. All rights reserved.
//

#import "TestGridPageTableViewCell.h"
#import "TestUIPageControl.h"
#import "Menu.h"
#import "MenuCollectionViewCellModel.h"
#import "MenuCollectionViewCell.h"
#import "TestOperationView.h"
#import "BGRefreshViewController.h"

@interface TestGridPageTableViewCell ()<MKUICollectionViewDelegateGridPageLayout>
@property(nonatomic,strong) TestOperationView *opertaionView;
@property(nonatomic,strong) MKUICollectionView *collectionView;
@property(nonatomic,strong) MKUIGridPageCollectionViewLayout *pageFlowLayout;
@property(nonatomic,strong) UIView<TestUIPageControlProtocol> *pageControl;
@property(nonatomic,strong) MKUIFlowLayoutConstraint *flowlayout;
@property(nonatomic,assign) NSInteger scrollStep;
@end

@implementation TestGridPageTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.opertaionView = [[TestOperationView alloc] init];
        [self.opertaionView.preButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
            [self.pageFlowLayout scrollToPageWithDistance:-1 animated:YES];
        } context:self];
        [self.opertaionView.nextButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
            [self.pageFlowLayout scrollToPageWithDistance:+1 animated:YES];
        } context:self];
        [self.opertaionView.leftButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
            self.scrollStep--;
            [self __refreshOperationView];
        } context:self];
        [self.opertaionView.rightButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
            self.scrollStep++;
            [self __refreshOperationView];
        } context:self];
        [self.opertaionView.cycleButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
            BOOL enableCycle = ![self.cellModel mk_boolForKeyPath:@"enableCycle" otherwise:YES];
            self.cellModel[@"enableCycle"] = @(enableCycle);
            [self __refreshGripLayout];
            [self __refreshOperationView];
            [self.pageFlowLayout invalidateLayout];
        } context:self];
        [self.opertaionView.refreshButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
            [self.collectionView reloadData];
        } context:self];
        
        [self.opertaionView.refreshBgButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
            NSInteger page = [self.pageFlowLayout currentPage];
            if(page!=NSNotFound){
                BGRefreshViewController *vc = [[BGRefreshViewController alloc] init];
                [vc view];
                [self.mk_viewControllerOfFirst.navigationController pushViewController:vc animated:YES];
                [vc.refreshButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
                    
                    [self.collectionView.model removeAllSectionModels];
                    [self.collectionView.model addCellModel:[self __gemAddMenuCM]];
                    [self.collectionView.model reloadCollectionViewData];
                    [self.pageFlowLayout reloadData];
                    [self __refreshGripLayout];
                    [self __refreshPageControl];
                    [self __refreshOperationView];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.mk_viewControllerOfFirst.navigationController popViewControllerAnimated:YES];
                    });
                } context:self];
            }
        } context:self];
        
        [self.opertaionView.addButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
            MKUICollectionViewSectionModel *sm = [[MKUICollectionViewSectionModel alloc] init];
            [sm addCellModel:[self __gemMenuCM:[Menu random]]];
            [sm addCellModel:[self __gemAddMenuCM]];
            
            [self.collectionView.model insertSectionModel:sm atIndex:self.collectionView.model.numberOfSections animated:YES completion:^(BOOL finished) {
                [self __refreshPageControl];
            }];
        } context:self];
        [self.opertaionView.deleteButton mk_addClickActionBlock:^(TestGridPageTableViewCell *self) {
            NSInteger page = self.pageFlowLayout.currentPage;
            if(page!=NSNotFound){
                NSArray<NSIndexPath *> *indexpaths = [self.pageFlowLayout itemIndexPathsForPage:page];
                [self.collectionView.model removeCellModelsAtIndexPaths:indexpaths];
                [self.collectionView performBatchUpdates:^{
                    [self.collectionView deleteItemsAtIndexPaths:indexpaths];
                } completion:^(BOOL finished) {
                    [self __refreshPageControl];
                }];
            }
        } context:self];
        [self.contentView addSubview:self.opertaionView];
        //
        //
        self.pageFlowLayout = [[MKUIGridPageCollectionViewLayout alloc] init];
        self.pageFlowLayout.interitemSpacing = 10;
        self.pageFlowLayout.itemSize = CGSizeMake(60, 60);
        self.pageFlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
//        self.pageFlowLayout.enableCycleScroll = YES;
        
        self.collectionView = [[MKUICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.pageFlowLayout];
        self.collectionView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.collectionView.layer.borderWidth = 1;
        
        self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast;
        self.collectionView.showsHorizontalScrollIndicator = NO;
        self.collectionView.model.forwardDelegate = self;
        [self.contentView addSubview:self.collectionView];
        
        @MK_WEAKIFY(self);
        MKUILayoutConstraintItemWrapper *w1 = [MKUILayoutConstraintItemWrapper wrapItem:self.collectionView sizeThatFitsBlock:^CGSize(MKUILayoutConstraintItemWrapper * _Nonnull wrapper, CGSize size, BOOL resizeItems) {
            @MK_NORMALIZE(self);
            return CGSizeMake(size.width, self.pageFlowLayout.itemSize.height+self.pageFlowLayout.sectionInset.top+self.pageFlowLayout.sectionInset.bottom);
        }];
        //
        self.pageControl = [[[self.class pageControlClass] alloc] init];
        [self.contentView addSubview:self.pageControl];
        
        self.flowlayout = [[MKUIFlowLayoutConstraint alloc] initWithItems:@[self.opertaionView,w1,self.pageControl] constraintParam:(MKUIFlowLayoutConstraintParam_V_T_C) contentInsets:MKUIEdgeInsetsMakeSameEdge(10) interitemSpacing:5];
        //
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.contentView.backgroundColor = [UIColor mk_colorWithLight:[UIColor whiteColor]];
        self.collectionView.backgroundColor = [UIColor mk_colorWithLight:[UIColor whiteColor]];
    }
    return self;
}
+ (Class)pageControlClass{
    return [TestUIPageControl class];
}
- (NSInteger)scrollStep{
    return [self.cellModel mk_integerForKeyPath:@"step" otherwise:0];
}
- (void)setScrollStep:(NSInteger)step{
    self.cellModel[@"step"] = @(step);
    [self __refreshGripLayout];
}
- (void)customLayoutSubviews{
    [super customLayoutSubviews];
    CGRect bounds = self.contentView.bounds;
    self.flowlayout.bounds = bounds;
    [self.flowlayout layoutItemsWithResizeItems:YES];
    [self __refreshPageControl];
}
- (CGSize)customSizeThatFits:(CGSize)size{
    return [self.flowlayout sizeThatFits:size resizeItems:YES];
}
- (void)customReloadCellModel{
    [super customReloadCellModel];
    [self reloadData];
}
- (MenuCollectionViewCellModel *)__gemMenuCM:(Menu *)menu{
    MenuCollectionViewCellModel *cm = [[MenuCollectionViewCellModel alloc] initWithModelObject:menu];
    cm.cellClass = [MenuCollectionViewCell class];
    @MK_WEAKIFY(self);
    cm.whenClick = ^(__kindof MKUICollectionViewCellModel * _Nonnull cellModel) {
        @MK_NORMALIZE(self);
        @MK_WEAKIFY(self);
        [self.collectionView.model removeCellModel:cellModel animated:YES completion:^(BOOL finished) {
            @MK_NORMALIZE(self);
            [self __refreshPageControl];
        }];
    };
    return cm;
}
- (MenuCollectionViewCellModel *)__gemAddMenuCM{
    MenuCollectionViewCellModel *cm = [[MenuCollectionViewCellModel alloc] initWithModelObject:[Menu addMenu]];
    cm.cellClass = [MenuCollectionViewCell class];
    @MK_WEAKIFY(self);
    cm.whenClick = ^(__kindof MKUICollectionViewCellModel * _Nonnull cellModel) {
        @MK_NORMALIZE(self);
        MenuCollectionViewCellModel *cm = [self __gemMenuCM:[Menu random]];
        NSIndexPath *indexpath = cellModel.indexPathInModel;
        [self.collectionView.model insertCellModel:cm atIndexPath:indexpath animated:YES completion:^(BOOL finished) {
            [self __refreshPageControl];
        }];
    };
    return cm;
}
- (void)reloadData{
    [self.collectionView.model removeAllSectionModels];
    NSArray<Menu *> *menus = self.cellModel.modelValue;
    for (Menu *menu in menus) {
        [self.collectionView.model addCellModel:[self __gemMenuCM:menu]];
    }
    if(menus.count){
        [self.collectionView.model addCellModel:[self __gemAddMenuCM]];
    }
    [self.collectionView.model reloadCollectionViewData];
    [self.collectionView layoutIfNeeded];
    [self __refreshGripLayout];
    [self __refreshPageControl];
    [self __refreshOperationView];
}
- (void)__refreshPageControl{
    self.pageControl.hidesForSinglePage = [self.cellModel mk_boolForKeyPath:@"hidesForSinglePage" otherwise:self.pageControl.hidesForSinglePage];
    self.pageControl.numberOfPages = self.pageFlowLayout.numberOfPages;
    self.pageControl.currentPage = self.pageFlowLayout.currentPage;
}
- (void)__refreshOperationView{
    NSInteger step = self.scrollStep;
    BOOL enableCycle = [self.cellModel mk_boolForKeyPath:@"enableCycle" otherwise:YES];
    self.opertaionView.stepLabel.text = [NSString stringWithFormat:@"Step:%@",@(step)];
    self.opertaionView.cycleButton.selected = enableCycle;
    [self.opertaionView setNeedsLayout];
}
- (void)tableView:(UITableView *)tableView willDisplayCellModel:(__kindof MKUITableViewCellModel *)cellModel{
    [self __refreshGripLayout];
    [self __refreshPageControl];
    [self __refreshOperationView];
}
- (void)__refreshGripLayout{
    BOOL enableCycle = [self.cellModel mk_boolForKeyPath:@"enableCycle" otherwise:YES];
    self.pageFlowLayout.enableCycleScroll = enableCycle;
    NSInteger currentPage = [self.cellModel mk_integerForKeyPath:@"currentPage" otherwise:0];
    self.pageFlowLayout.currentPage = currentPage;
    
    NSInteger step = self.scrollStep;
    BOOL autoScroll = step!=0;
    if(autoScroll){
        [self.pageFlowLayout startAutoScrollingWithDistance:step duration:2];
    }else{
        [self.pageFlowLayout stopAutoScrolling];
    }
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCellModel:(__kindof MKUITableViewCellModel *)cellModel{
    [self.pageFlowLayout stopAutoScrolling];
}
- (void)collectionView:(UICollectionView *)collectionView gridPageLayout:(MKUIGridPageCollectionViewLayout *)collectionViewLayout didScrollToPage:(NSInteger)page{
    self.cellModel[@"currentPage"] = @(page);
    [self __refreshPageControl];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(![self.pageControl respondsToSelector:@selector(scrollToPageIndex:progress:)]){
        return;
    }
    CGPoint offset = scrollView.contentOffset;
    NSInteger toPage = 0;
    CGFloat progress = [self.pageFlowLayout scrollProgressWithContentOffset:offset toPage:&toPage];
    NSInteger pageIndex = toPage;
    [self.pageControl scrollToPageIndex:pageIndex progress:progress];
}
@end

@implementation TestGridPageTableViewCell_1
+ (Class)pageControlClass{
    return [TestUIPageControl_1 class];
}
@end
@implementation TestGridPageTableViewCell_2
+ (Class)pageControlClass{
    return [TestUIPageControl_2 class];
}
@end
@implementation TestGridPageTableViewCell_3
+ (Class)pageControlClass{
    return [TestUIPageControl_3 class];
}
@end
@implementation TestGridPageTableViewCell_4
+ (Class)pageControlClass{
    return [TestUIPageControl_4 class];
}
@end
@implementation TestGridPageTableViewCell_5
+ (Class)pageControlClass{
    return [TestUIPageControl_5 class];
}
@end
